package mvc.view.forms;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.table.TableModel;

import utils.Tracer;
import mvc.model.IModel;
import mvc.view.IModelView;
import mvc.view.forms.buttons.CViewActionsFactory;
import mvc.view.forms.buttons.VIEW_ACTIONS;
import mvc.view.forms.buttons.toolbar.CToolbarButton;

public abstract class CGridForm extends CMDIChild implements ActionListener, IModelView{
	private JTextField txtA;
	private JToolBar toolBar;
	private JToolBar tableBar;
	protected JTable table;
	
	private IModel model;
	private CViewActionsFactory actionFactory;
	
	public CGridForm() {		
// toolbar 
		JPanel northPanel = new JPanel();
		getContentPane().add(northPanel, BorderLayout.NORTH);
		northPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

		toolBar = new JToolBar();
		addToolbarButton(toolBar, "Add", VIEW_ACTIONS.ADD);
		addToolbarButton(toolBar,"Delete", VIEW_ACTIONS.DELETE);
		addToolbarButton(toolBar, "Copy", VIEW_ACTIONS.COPY);
		northPanel.add(toolBar);
//table		
		table = new JTable();
		JScrollPane scrollPane = new JScrollPane(table);
		getContentPane().add(scrollPane);
		
//table bar
		JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.SOUTH);
		panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
		tableBar = new JToolBar();
		panel.add(tableBar);
		addToolbarButton(tableBar, "Next", VIEW_ACTIONS.NEXT);
		addToolbarButton(tableBar, "Previous", VIEW_ACTIONS.PREVIOUS);		
		txtA = new JTextField("A", 3);
		tableBar.add(txtA);
		addToolbarButton(tableBar, "Filter", VIEW_ACTIONS.FILTER);
	}
	
	private void addToolbarButton(JToolBar pToolbar, String pCaption, VIEW_ACTIONS pActionType){
		CToolbarButton newButton = new CToolbarButton(pCaption, pActionType);
		pToolbar.add(newButton);
		newButton.addActionListener(this);		
	}
	
	@Override
	public void setModel(IModel pModel){
		model = pModel;
		table.setModel((TableModel) model);
	}
	
	@Override
  public void actionPerformed(ActionEvent pActionEvent) {
		Tracer.trace(pActionEvent.getActionCommand());
		CToolbarButton pressedButton = (CToolbarButton) pActionEvent.getSource();
	  CViewActionsFactory.executeAction(pressedButton.getModelAction(), model);
  }
	
}
